#include "keywords.h"

#include "asr_stream.h"
#include "port_audio.h"

#include "conf.h"

#include <memory>
#include <signal.h>
#include <unistd.h>
#include <string>

namespace {
    std::unique_ptr<AsrStream>  asr;
    std::unique_ptr<KeywordSpotter>  kws;

    int asr_inputStream_callback(const float* audioData, int numSamples) {
        if (kws) {
            kws->DetectKeyword(static_cast<int>(asr->sample_rate()), audioData, numSamples);
        }
        return 0;
    }

    // 回调函数，当检测到关键词时调用
    void OnKeywordDetected(const std::string &keyword) {
        sys_log("Detected keyword: %s", keyword.c_str());
        sys_log("you can say the keywords again.");
    }

    void signalHandler(int signum) {
        sys_log("signal handler .... exit ......");

        if (asr) {
            sys_log("asr pause.");
            asr->pause();
        }

        if (kws)    kws.reset();

        if (asr)    asr.reset();

        exit(signum);  // 释放资源
    }
}


int main(void)
{
    signal(SIGINT, signalHandler);

    // 初始化全局的 portAudio 库
    std::unique_ptr<PortAudioManager> pam = std::make_unique<PortAudioManager>();

    // 初始化语音识别类
    asr = std::make_unique<AsrStream>(
        "/opt/sherpa-onnx/sherpa-onnx-streaming-zipformer-bilingual-zh-en"
    );
    asr->setReadInStreamCallback(asr_inputStream_callback);

    // 初始化关键词检测
    kws = std::make_unique<KeywordSpotter> (
        "/opt/sherpa-onnx/kws-zipformer-wenetspeech", 
        "/opt/sherpa-onnx/kws-zipformer-wenetspeech/outputMykeywords.txt");
    kws->SetKeywordDetectedCallback(OnKeywordDetected);

    asr->resume();

    sys_log("you can say the keywords.");

    // 10 minute asr input test.
    sleep(60 * 10);

    exit(0);
}

